package com.kczd.jinlan.view.classify.fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kczd.jinlan.R;
import com.kczd.jinlan.adapter.recycleviewadapter.RecyclerViewGradviewAdapter;
import com.kczd.jinlan.model.Goods;
import com.kczd.jinlan.myview.pulltoreflush.PullLoadMoreRecyclerView;
import com.kczd.jinlan.utils.Config;
import com.kczd.jinlan.view.classify.FoodDetailsActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * yang_g
 * 默认
 * Created by Administrator on 2017/5/22.
 */

public class DefaultFragment extends Fragment {
    private static final String TAG="DefaultFragment.class";
    String url = Config.net_addr + "goods/goods_list";

    private View view;
    private PullLoadMoreRecyclerView mPullLoadMoreRecyclerView;
    // private int mCount = 1;
    private RecyclerViewGradviewAdapter mRecyclerViewAdapter;
    public  List<Goods> goodslist;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.moren_fragment, null);

        mPullLoadMoreRecyclerView = (PullLoadMoreRecyclerView) view.findViewById(R.id.pullLoadMoreRecyclerView);
        //mPullLoadMoreRecyclerView.setRefreshing(true);
        mPullLoadMoreRecyclerView.setGridLayout(2);
        mRecyclerViewAdapter = new RecyclerViewGradviewAdapter(getActivity());
        mPullLoadMoreRecyclerView.setAdapter(mRecyclerViewAdapter);
        //获取网络数据
        HandlerData();


        return view;
    }
    private void HandlerData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                getServiceData();
            }
        }).start();
    }



    public void getServiceData() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("id",FoodDetailsActivity.classid)
                .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            Log.e(TAG,val);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(Config.code.equals(jsonResult.getString("code"))) {
                    JSONArray jsonArray= jsonResult.getJSONArray("data");
                    goodslist=new ArrayList<>();
                    for(int i=0;i<jsonArray.length();i++)
                    {
                        JSONObject jbgoods=jsonArray.getJSONObject(i);
                        Goods goods=new Goods();
                        goods.setTitle(jbgoods.getString("goods_name"));
                        goods.setPrice(jbgoods.getString("market_price"));
                        goods.setOldprice(jbgoods.getString("cost_price"));
                        goods.setCid(jbgoods.getString("goods_id"));
                        goods.setWeight_dai(jbgoods.getString("weight"));//商品每袋重量
                        goods.setPrice_kg(jbgoods.getString("shop_price"));//商品每千克的价钱
                        goods.setImage(jbgoods.getString("original_img"));
                        goods.setCount(1);
                        goodslist.add(goods);
                    }
                    getData();
                    mPullLoadMoreRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreListener());
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    private void getData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRecyclerViewAdapter.addAllData(goodslist);
                mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
            }
        }, 1000);
    }
    class PullLoadMoreListener implements PullLoadMoreRecyclerView.PullLoadMoreListener {
        @Override
        public void onRefresh() {
            setRefresh();
            getData();
        }

        @Override
        public void onLoadMore() {
            //  mCount = mCount + 1;
            setRefresh();
            getData();
        }
    }

    private void setRefresh() {
        mRecyclerViewAdapter.clearData();
        //  mCount = 1;

    }

}
